# Patchless XMLRPC Service for Django
# Kind of hacky, and stolen from Crast on irc.freenode.net:#django
# Self documents as well, so if you call it from outside of an XML-RPC Client
# it tells you about itself and its methods
#
# Brendan W. McAdams <brendan.mcadams@thewintergrp.com>

# SimpleXMLRPCDispatcher lets us register xml-rpc calls w/o
# running a full XMLRPC Server.  It's up to us to dispatch data

from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.http import HttpResponse
from bcdbd.main.models import Barcode, Field
from bcdbd.rpc.plugins import base
import sys

# Create a Dispatcher; this handles the calls and translates info to function maps
if sys.version_info[0] >= 2 and sys.version_info[1] >= 5:
	dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None)
else:
	dispatcher = SimpleXMLRPCDispatcher()


def rpc_handler(request):
        """
        the actual handler:
        if you setup your urls.py properly, all calls to the xml-rpc service
        should be routed through here.
        If post data is defined, it assumes it's XML-RPC and tries to process as such
        Empty post assumes you're viewing from a browser and tells you about the service.
        """

        response = HttpResponse()
        if len(request.POST):
                response.write(dispatcher._marshaled_dispatch(request.raw_post_data))
        else:
                response.write("<b>This is an XML-RPC Service.</b><br>")
                response.write("You need to invoke it using an XML-RPC Client!<br>")

        response['Content-length'] = str(len(response.content))
        return response

### -- Copyright (C) 2007 Alexis ROBERT --- ###
def getProtocolVersion():
	return 1.1

def isBarcode(barcode):
	if base.getBarcode(barcode): return 1
	else: return 0

def isBarcodeLocal(barcode):
	if base.getBarcodeByPlugin(barcode, ["local"]): return 1
	else: return 0
	
def getBarcodeTitle(barcode):
	b = base.getBarcode(barcode)
	if b:
		return b.title
	else:
		return ""

def getBarcodeFields(barcode):
	b = base.getBarcode(barcode)
	if b:
		return b.fields
	else:
		return {}
	
dispatcher.register_function(getProtocolVersion, 'getProtocolVersion')
dispatcher.register_function(isBarcode, 'isBarcode')
dispatcher.register_function(isBarcodeLocal, 'isBarcodeLocal')
dispatcher.register_function(getBarcodeTitle, 'getBarcodeTitle')
dispatcher.register_function(getBarcodeFields, 'getBarcodeFields')
### -- Copyright (C) 2007 Alexis ROBERT --- ###
